package com.ruoyi.apm.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.github.pagehelper.util.StringUtil;
import com.ruoyi.apm.http.client.HttpSequenceHandle;
import com.ruoyi.apm.model.*;
import com.ruoyi.apm.service.DockDataConfigService;
import com.ruoyi.apm.service.HttpRequestService;
import com.ruoyi.apm.service.HttpSequenceService;
import com.ruoyi.apm.util.GuidGenerator;
import com.ruoyi.apm.util.PostManResolver;
import com.ruoyi.common.constant.ScheduleConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.util.ScheduleUtils;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/dockManage")
public class MonitorEditController {

	protected static final Logger LOGGER = LoggerFactory.getLogger(MonitorEditController.class);

	@Autowired
	private HttpSequenceService httpSequenceService;
	
	@Autowired
	private HttpRequestService httpRequestService;

	@Autowired
	private DockDataConfigService dockDataConfigService;


    /*@RequestMapping("/addSingleMonitor")
    public String addSingleMonitor(ModelMap map) {    	
    	HttpRequestForm form = new HttpRequestForm();
    	map.put("form", form);
    	return "monitor_add_single";
    }*/

	/**
	 * 添加系统名称
	 * @param systemName
	 * @return
	 */
	@RequestMapping(value="/addGroup",method=RequestMethod.POST)
    public AjaxResult addGroup(@RequestParam("systemName") String systemName){
		return AjaxResult.success(httpSequenceService.addHttpSystem(systemName));
    }

	/**
	 * 获取系统名称
	 * @return
	 */
    @RequestMapping(value="/getGroups")
    public AjaxResult addGroup(){
		return AjaxResult.success(httpSequenceService.getAllSystem());
    }

    /*@RequestMapping(value="/saveSingleMonitor",method=RequestMethod.POST)
    public boolean saveSingleMonitor(@ModelAttribute HttpRequestForm form){
		try{
			//添加
			if(StringUtil.isEmpty(form.getGuid())){
				HttpSequence httpSequence = HttpSequence.getHttpSequence(form);
				httpSequence.setGuid(GuidGenerator.generate());
				HttpRequest httpRequest = HttpRequest.getHttpRequest(form);
				httpRequest.setGuid(GuidGenerator.generate());
				httpRequest.setPguid(httpSequence.getGuid());
				httpSequenceService.insert(httpSequence);
				httpRequestService.insertHttpRequest(httpRequest);
			}else{
				//修改
				HttpSequence httpSequence = HttpSequence.getHttpSequence(form);
				HttpRequest httpRequest = HttpRequest.getHttpRequest(form);
				httpSequenceService.update(httpSequence);
				httpRequestService.updateHttpRequest(httpRequest);
			}
	        return true;
		}catch(Exception e){
			LOGGER.error("错误日志",e);
			return false;
		}
    }

    @RequestMapping("/editSingleMonitor")
    public String editSingleMonitor(ModelMap map, HttpServletRequest request) {
    	String guid = request.getParameter("guid");
    	HttpSequence httpSequence = httpSequenceService.getByGuid(guid);
    	List<HttpRequest> list = httpRequestService.getHttpRequestListByPguid(guid);
    	HttpRequest httpRequest = list.get(0);
    	HttpRequestForm form = HttpRequestForm.getHttpRequestForm(httpSequence, httpRequest);
    	map.put("form", form);
    	return "monitor_add_single";
    }*/

	/**
	 * 新增编辑任务弹窗回显
	 * @param guid
	 * @return
	 */
    @RequestMapping("/editSequenceMonitor")
    public AjaxResult addSequenceMonitor(String guid) {
		Map<String,Object> result = new HashMap<>();
    	HttpSequence httpSequence;
    	if(StringUtil.isEmpty(guid)){
    		httpSequence = new HttpSequence();
    		httpSequence.setType(HttpSequence.MonitorType.SEQUENCE);
    	}else{
        	httpSequence = httpSequenceService.getByGuid(guid);
        	DockDataConfig dockDataConfig = httpSequenceService.getDockDataConfig(guid);
        	httpSequence.setDockDataConfig(dockDataConfig);
        	List<HttpRequest> list = httpRequestService.getHttpRequestListByPguid(guid);
        	httpSequence.setHttpRequest(list);
    	}
		result.put("form", httpSequence);
    	List<HttpSystem> systems = httpSequenceService.getAllSystem();
		result.put("systems", systems);
		result.put("dataSources", DataSourceType.values());
    	return AjaxResult.success(result);
    }

	/**
	 * 新增、编辑任务
	 * @param httpSequence
	 * @return
	 */
    @RequestMapping(value="/saveSequenceMonitor",method=RequestMethod.POST)
    public AjaxResult saveSequenceMonitor(@RequestBody HttpSequence httpSequence){
		try{
			httpSequenceService.eduitSaveHttpSequence(httpSequence);
	        return AjaxResult.success("成功");
		}catch(Exception e){
			LOGGER.error("错误日志",e);
			return AjaxResult.error("失败");
		}
    }

    /*@RequestMapping(value="/resolverPostMan",method=RequestMethod.POST)
    public ArrayList<HttpRequest> resolverPostMan(@RequestParam("postmanScript") String postmanScript){
		ArrayList<HttpRequest> list = new ArrayList<HttpRequest>();
		try{
			list = PostManResolver.readV2FromJsonText(postmanScript);
			return list;
		}catch(Exception e){
			LOGGER.error("错误日志",e);
			return null;
		}
    }*/

	/**
	 * 接口测试
	 * @param httpSequence
	 * @return
	 */
    @RequestMapping(value="/testApi",method=RequestMethod.POST)
    public AjaxResult testApi(@RequestBody HttpSequence httpSequence){
		try{
			 ArrayList<APITestForm> list = new ArrayList<APITestForm>();
	    	//执行接口探测
	    	HttpSequenceHandle httpSequenceHandle = new HttpSequenceHandle(httpSequence);
	    	httpSequenceHandle.test();
	    	List<HttpRequest> requests = httpSequence.getHttpRequest();
	    	for(int i=0;i<requests.size();i++){
	    		HttpRequest request = requests.get(i);
	    		HttpRequestLog log = httpSequenceHandle.httpRequestLogList.get(i);
		    	APITestForm form = new APITestForm();
		    	form.setName(request.getName());
		    	form.setCostTime(log.getCostTime());
		    	form.setLog(log.getLog());
		    	form.setResponseBody(log.getResponseBody());
		    	form.setSort(request.getSort());
		    	form.setStatus(log.isStatus()?"成功":"失败");
		    	form.setStatusCode(log.getStatusCode());
		    	form.setUrl(request.getUrl());
		    	HashMap<String, String>  map = request.getVariablesMap();
				StringBuffer varables = new StringBuffer();
				if(map!=null){
					for (String key : map.keySet()) {
						varables.append(key).append("=").append(httpSequenceHandle.getVariables(key));
					}
				}
		    	form.setVariables(varables.toString());
		    	list.add(form);
	    	}
	    	return AjaxResult.success(list);
		}catch(Exception e){
			LOGGER.error("错误日志",e);
			return AjaxResult.error("失败");
		}
	}

	/**
	 * 执行一次
	 * @param guid
	 * @return
	 */
	@GetMapping(value="/excuteApi")
	public AjaxResult excuteApi(String guid){
		return AjaxResult.success(httpRequestService.runJob(guid));
	}
}
